﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraTab;

namespace ProgNetDxComponents.Controls.Editors
{
    public partial class MultiEditBaseTab : XtraTabPage
    {
        private DataTable _DataSource;
        private string _ValueMember;
        private string _DisplayMember;
        public MultiEditBaseTab()
        {
            InitializeComponent();
        }
        protected DataView DataView = new DataView();
        public event EventHandler<RowSelectEventArgs> RowSelected;

        protected virtual void OnRowSelected()
        {
            DataRow row = GetSelectedRow();
            if (RowSelected != null && row != null)
                RowSelected(this, new RowSelectEventArgs(row));
        }

        public virtual  DataRow GetSelectedRow()
        {
            return null;
        }

        public virtual DataTable DataSource
        {
            get { return _DataSource; }
            set
            {
                _DataSource = value;
                DataView.Table = value;
            }
        }

        public virtual void FocusValue(object editValue)
        {

        }

        public string Filter
        {
            get { return DataView.RowFilter; }
            set { DataView.RowFilter = value; }
        }
        
        public virtual string ValueMember
        {
            get { return _ValueMember; }
            set { _ValueMember = value; }
        }

        public string DisplayMember
        {
            get
            {
                if (string.IsNullOrEmpty(_DisplayMember))
                    return ValueMember;
                return _DisplayMember;
            }
            set { _DisplayMember = value; }
        }

        /// <summary>
        /// Checks if DataSource contains row for whitch ValueMember = editValue
        /// </summary>
        /// <param name="editValue"></param>
        /// <returns></returns>
        public bool ValidateValue(object editValue)
        {
            string val = editValue.AsString();
            if (val.IsNull())
            {
                return true;
            }
            DataTable dt = DataView.ToTable();
            DataRow r = dt.SelectFirstRow(ValueMember + " = " + val.EscapeSql(), null, DataViewRowState.CurrentRows);
            return r != null;
        }
    }
}
